package com.jiaodacailei.ttv;

import org.jcodec.api.awt.AWTSequenceEncoder;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.io.SeekableByteChannel;
import org.jcodec.common.model.ColorSpace;
import org.jcodec.common.model.Picture;
import org.jcodec.common.model.Size;
import org.jcodec.scale.AWTUtil;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Hello world!
 *
 */
public class App 
{

    public static void main(String[] args) throws IOException {
        // 设置视频文件输出路径
        File outputFile = new File("output_video.mp4");

        // 设置视频的大小和帧率
        Size size = new Size(640, 480);
        int frameRate = 30;

        // 创建一个SeekableByteChannel来写入视频文件
        // SeekableByteChannel out = NIOUtils.writableChannel(outputFile);

        // 创建AWTSequenceEncoder来编码视频
        AWTSequenceEncoder encoder = AWTSequenceEncoder.createSequenceEncoder(outputFile, frameRate);

        // 生成视频帧
        for (int i = 0; i < frameRate * 5; i++) {
            // 创建一个示例的彩色渐变帧
            Picture frame = createColorGradientFrame(size.getWidth(), size.getHeight(), i);

            // 使用 encodeNativeFrame 将图像帧编码并添加到视频
            encoder.encodeNativeFrame(frame);

            // 可选：在控制台输出当前帧的进度
            System.out.println("Frame " + (i + 1) + " encoded");
        }

        // 完成编码并关闭输出流
        encoder.finish();
        // out.close();

        System.out.println("视频生成完毕！");
    }

    // 创建一个彩色渐变帧
    private static Picture createColorGradientFrame(int width, int height, int frameNumber) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics = image.createGraphics();

        // 计算彩色渐变
        int colorValue = frameNumber * 255 / (width - 1);
        Color color = new Color(colorValue, colorValue, colorValue);

        // 在图像上绘制彩色矩形
        graphics.setColor(color);
        graphics.fillRect(0, 0, width, height);
        graphics.dispose();

        // 将 BufferedImage 转换为 JCodec 的 Picture 对象
        return AWTUtil.fromBufferedImage(image, ColorSpace.RGB);
    }
}
